package com.ruoyi.file.minio;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MinioClientProxy implements IUpFileOperation {

    /**
     * 文件时间戳格式
     */
    SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");

    /**
     * 文件处理类
     */
    @Autowired
    private MinioClient minioClient;

    /**
     * 桶名称
     */
     @Value("${minio.up-file.bucket-name}")
     private String bucketName;


    @Override
    public String upFile(File file) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        FileInputStream fps = new FileInputStream(file);
        String filePrefix = df.format(new Date());
        String fPath = filePrefix + ".jpg";

        // 存储桶不存在则创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            setPublicPolicy(bucketName);
        }

        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)   //桶名
                .object(fPath) //要生成的对象名
                .stream(fps,file.length(),-1)
                .contentType("image/jpeg")
                .build());
        fps.close();

        String objectUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(fPath)
                .method(Method.GET)
                .build());

       int index = objectUrl.indexOf("?");
       objectUrl = objectUrl.substring(0, index);

       return objectUrl;
    }

    /**
     * 设置桶权限为public
     * @param bucketName 桶名称
     */
    private void setPublicPolicy(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        String policy = "{\"Version\":\"2012-10-17\"," +
                "\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":" +
                "{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"," +
                "\"s3:GetBucketLocation\"],\"Resource\":[\"arn:aws:s3:::" + bucketName +
                "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\"],\"Resource\":[\"arn:aws:s3:::" +
                bucketName +
                "/*\"]}]}";
        minioClient.setBucketPolicy(
                SetBucketPolicyArgs.builder()
                        .bucket(bucketName)
                        .config(policy)
                        .build());
    }



}
